import AntModal from '@/components/pt/dialog/AntModal'
import AdvanceTable from '@/components/pt/table/AdvanceTable'
import { addBizPayment, updateBizPayment } from '@/api/biz/bizPayment'
import { getBizCustomerPayable } from '@/api/biz/bizCustomerPayable'
import { getBizCustomerDetail,listAllBizCustomerAccount,getBizPaymentDetailInfo } from '@/api/biz/bizCustomerAccount'

export default {
  name: 'CreateForm',
  props: {
    customerIdOptions: {
      type: Array,
      required: false
    },
    payOptions: {
      type: Array,
      required: false
    },
    accountCode: {
      type: String,
      required: false
    },
  },
  components: {
    AntModal,
    AdvanceTable
  },
  data () {
    return {
      open: false,
      closeDialog: true,
      spinning: false,
      delayTime: 100,
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      loading: false,
      disabled: false,
      total: 0,
      id: undefined,
      accountOptions: [],
      selectedRowKeys:[],
      selectedAccountRowKeys:[],
      multipleAccount:false,
      multiple:false,
      formTitle: '新增收款单',
      // 表单参数
      form: {},
      rules: {
        customerId: [{ required: true, message: '客户不能为空', trigger: 'blur' }],

        orderType: [{ required: true, message: '订单类型不能为空', trigger: 'blur' }]
      },
      columns: [
        {
          title: '销售单号',
          dataIndex:'orderNumber',
          align: 'center',
        },
        {
          title: '日期',
          dataIndex:'orderDate',
          align: 'center'
        },
        {
          title: '金额',
          dataIndex:'totalAmount',
          align: 'center'
        },
        {
          title: '已结算额',
          dataIndex:'collectedAmount',
          align: 'center'
        },
        {
          title: '未结结算',
          align: 'center',
          scopedSlots: {
            customRender: 'nopaySlot'
          }
        },
        {
          title: '本次结算',
          dataIndex:'amount',
          align: 'center',
          scopedSlots: {
            customRender: 'curSlot'
          }
        }
      ],
      columns1: [
        {
          title: '销售单号',
          dataIndex:'orderNumber',
          align: 'center',
        },
        {
          title: '日期',
          dataIndex:'orderDate',
          align: 'center'
        },
        {
          title: '金额',
          dataIndex:'totalAmount',
          align: 'center'
        },
        // {
        //   title: '本次',
        //   dataIndex:'collectedAmount',
        //   align: 'center'
        // },
        // {
        //   title: '未结算额',
        //   align: 'center',
        //   scopedSlots: {
        //     customRender: 'nopaySlot'
        //   }
        // },
        {
          title: '已结算',
          dataIndex:'payAmount',
          align: 'center'
        }
      ],
      
      columns2: [
        {
          title: '收款账户',
          dataIndex:'payAccount',
          align: 'center',
        },
        {
          title: '收款金额',
          dataIndex:'payAmount',
          align: 'center',
        },
        {
          title: '备注',
          dataIndex:'remark',
          align: 'center',
        },
      ],
      
      columns3: [
        {
          title: '销售单号',
          dataIndex:'orderNumber',
          align: 'center',
        },
        {
          title: '日期',
          dataIndex:'orderDate',
          align: 'center'
        },
        {
          title: '金额',
          dataIndex:'totalAmount',
          align: 'center'
        },
        // {
        //   title: '已结算额',
        //   dataIndex:'collectedAmount',
        //   align: 'center'
        // },
        // {
        //   title: '未结算额',
        //   align: 'center',
        //   scopedSlots: {
        //     customRender: 'nopaySlot'
        //   }
        // },
        {
          title: '本次结算',
          dataIndex:'collectedAmount',
          align: 'center',
          scopedSlots: {
            customRender: 'curSlot'
          }
        }
      ],
      
      columns4: [
        {
          title: '收款账户',
          dataIndex:'payAccount',
          align: 'center',
          scopedSlots: {
            customRender: 'payAccount'
          }
        },
        {
          title: '收款金额',
          dataIndex:'payAmount',
          align: 'center',
          scopedSlots: {
            customRender: 'payAmount'
          }
        },
        {
          title: '备注',
          dataIndex:'remark',
          align: 'center',
          scopedSlots: {
            customRender: 'remark'
          }
        },
        {
          title: '操作',
          dataIndex:'operator',
          align: 'center',
          scopedSlots: {
            customRender: 'operator'
          }
        },
      ],
    }
  },
  filters: {},
  created () {
    listAllBizCustomerAccount().then((response) => {
      this.accountOptions = response.data
    })
  },
  computed: {},
  watch: {
    "form.id": {
      handler(val) {
        if (val) {
          this.$nextTick(() => (
            getBizPaymentDetailInfo(val).then(response => {
              this.form.customerId = response.data.customerId
              this.form.customerName = response.data.customerName
              this.form.hasAmount = response.data.totalAmount
              this.form.paymentBillList = (response.data.paymentBillList || []).map(v=>(v.collectedAmount = v.payAmount || 0,v))
              this.form.paymentDetailList = response.data.paymentDetailList
              this.$forceUpdate();
            })
            
          ))
        }
      },
      immediate: true,
    },
  },
  mounted () {},
  methods: {
    onClose () {
      this.open = false
      this.reset()
      this.$emit('close')
    },
    // 取消按钮
    cancel () {
      this.open = false
      this.reset()
      this.$emit('close')
    },
    // 表单重置
    reset () {
      this.form = {
        id: undefined,

        payCode: undefined,

        supplierCode: undefined,

        supplierName: undefined,

        payAmount: undefined,

        purchaseDate: undefined,

        hasAmount: undefined,

        remark: undefined,

        payDate: undefined,

        payAccount: undefined,
        zeroAmount:undefined

      }
    },
    /** 新增按钮操作 */
    handleAdd (row) {
      this.reset()
      this.open = true
      this.formTitle = row.id ? '修改收款单' : '新增收款单';
      this.form = row
    },
    handleAddPay(){
      this.form.paymentDetailList.push({payAmount:0})
    },
    handleView(row){
      this.reset()
      this.open = true
      this.formTitle = '收款单明细';
      this.form = row
    },
    
    handleAllocation(){
      let total = this.form.paymentDetailList.reduce((pre,cur)=>{
        return this.$toDecimal(pre + +cur.payAmount)
      },0)
      this.form.paymentBillList = this.form.paymentBillList.map(v=>{
        let nopay = v.totalAmount
        if(+total >= +nopay ){
          v.collectedAmount = nopay
          total = this.$toDecimal(total - nopay)
        }else if(+total < +nopay && +total >=0){
          v.collectedAmount = total
          total = 0
        }else{
          v.collectedAmount = 0
        }
        return v
      })
      this.amountChange()
    },
    
    /**
     * @汇总收款金额
     */
     amountChange(){
      let total = this.form.paymentBillList.reduce((pre,cur)=>{
        return this.$toDecimal(pre + +cur.collectedAmount)
      },0)
      this.$set(this.form,'payAmount',total)
    },
    
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.multiple = selectedRowKeys.length
    },
    onAccountSelectChange(selectedRowKeys, selectedRows) {
      this.selectedAccountRowKeys = selectedRowKeys
      this.multipleAccount = selectedRowKeys.length
    },
    handleDelete(){
      if (!this.selectedAccountRowKeys.length) {
        this.$message.error(
          '请选择要删除的数据',
          3
        )
        return
      }
      this.$confirm({
        title: '确认删除所选中数据?',
        onOk: () => {
          this.form.paymentDetailList = this.form.paymentDetailList.filter((v, index) => !this.selectedAccountRowKeys.includes(index) && !this.selectedAccountRowKeys.includes(v.id))
          this.selectedAccountRowKeys = []
          this.multipleAccount = false
          this.$message.success(
            '删除成功',
            3
          )
        }
      })
    },
    submitEdit(){
      console.log('this.form :>> ', this.form);
      this.disabled = true
      this.$refs.form.validate(valid => {
        if (valid) {
          // this.form.payableDetails = this.form.detailList
          const saveForm = JSON.parse(JSON.stringify(this.form))
          updateBizPayment(saveForm).then(response => {
            this.$message.success('操作成功', 3)
              this.$emit('ok')
              this.open = false
              this.$emit('close')
              this.disabled = false
          })
        } else {
          this.disabled = false
          return false
        }
      })
    },
    handleDeleteRows() {
      if (!this.selectedRowKeys.length) {
        this.$message.error(
          '请选择要删除的数据',
          3
        )
        return
      }
      this.$confirm({
        title: '确认删除所选中数据?',
        onOk: () => {
          // this.form.paymentBillList = this.form.paymentBillList.filter((v, index) => !this.selectedRowKeys.includes(index) && !this.selectedRowKeys.includes(v.id))
          // this.selectedRowKeys = []
          // this.multiple = false
          // this.$message.success(
          //   '删除成功',
          //   3
          // )
          delBizCustomerAccountDetail(this.selectedRowKeys.join(',')).then(res=>{
            if(res.code == 200) {
                this.$message.success(
                  '删除成功',
                  3
                )
                this.getDetail()
            }else{
              this.message.error(res.msg)
            }
          })
        }
      })
    },
    /** 提交按钮 */
    submitForm: function (closeDialog) {
      this.closeDialog = closeDialog
      this.disabled = true
      this.$refs.form.validate(valid => {
        if (valid) {
          this.form.payableDetails = this.form.detailList
          const saveForm = JSON.parse(JSON.stringify(this.form))
          addBizPayment(saveForm).then(response => {
            this.$message.success('新增成功', 3)
              this.$emit('ok')
              this.open = false
              this.$emit('ok')
              this.$emit('close')
              this.disabled = false
          })
        } else {
          this.disabled = false
          return false
        }
      })
    },
    back () {
      const index = '/biz/bizpayable/index'
      this.$router.push(index)
    },

  }
}
